<?php
class Post extends Model{

	public static function getAttributes(){
		return array('id','uid','title','summary','created','updated','flag');
	}
	/**
	 *
	 * 获取全部文章列表
	 */
	function getAllPost($where=array(),$order='',$limit=10,$offset=0){
		$postlist = $this->findAll($where,$order,$offset,$limit);
		$total = $this->getCount();
		if(count($postlist)>0){
			$M_user = new User;
			$_uids = array();
			$_ids = array();
			foreach($postlist as $v){
				$_uids[] = $v['uid'];
				$_ids[] = $v['id'];
			}
			$s_uids = implode(',',$_uids);
			$s_ids = implode(',',$_ids);
			//获取用户信息
			$user_info = $M_user->findAll(array('in'=>array('id'=>$s_uids)));
			$_user = array();
			foreach($user_info as $k=>$v){
				$_user[$v['id']] = $v;
			}
			//获取内容信息
			$M_content = new Postcontent();
			$content = $M_content->findAll(array('in'=>array('id'=>$s_ids)));
			$_content = array();
			foreach($content as $k=>$v){
				$_content[$v['id']] = $v;
			}
			foreach($postlist as &$v){
				$v['username'] = $_user[$v['uid']]['username'];
				$v['url'] = $this->createUrl('post/detail',array('id'=>$v['id']));
				$v['content'] = $_content[$v['id']]['content'];
			}
		}
		$postlist['total'] = $total;
		return $postlist;
	}

	function getPostById($id){
		$where = array('id'=>$id);
		$post = $this->find($where);
		$M_user = new User;
		$user = $M_user->find(array('id'=>$post['uid']));
		$M_content = new Postcontent();
		$content = $M_content->find(array('id'=>$id));
		$post['username'] = $user['username'];
		$post['content'] = $content['content'];
		return $post;
	}

	/**
	 * 添加新文章
	 * @param $post
	 */
	function addPost($post){
		$post['summary'] = substr($post['content'],0,250);
		if($id = $this->insert($post)){
			$M_postContent = new Postcontent();
			$content['id'] = $id;
			$content['content'] = $post['content'];
			$M_postContent->insert($content);
			return true;
		}
		return false;

	}

	/**
	 *
	 */


}